<template>
  <div class="chat-mid">
    <!-- 错误边界 -->
    <div v-if="error" class="error-boundary">
      <div class="error-content">
        <i class="icon-error"></i>
        <h3>出现了一些问题</h3>
        <p>{{ error }}</p>
        <button @click="handleRetry" class="retry-btn">重试</button>
      </div>
    </div>

    <!-- 正常内容 -->
    <template v-else>
      <!-- 加载状态 -->
      <div v-if="loading" class="loading-state">
        <div class="loading-spinner"></div>
        <p>加载中...</p>
      </div>

      <!-- 聊天内容 -->
      <div v-else class="chat-content">
        <!-- 消息历史记录 -->
        <MessageHistory
          :messages="messages"
          :loading="messagesLoading"
          :has-more="hasMoreMessages"
          :typing-users="typingUsers"
          @load-more="handleLoadMore"
        />

        <!-- 消息输入框 -->
        <MessageInput
          :placeholder="inputPlaceholder"
          :disabled="inputDisabled"
          @send="handleSendMessage"
          @typing="handleTyping"
        />
      </div>
    </template>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted, onUnmounted } from 'vue'
import MessageHistory from './MessageHistory.vue'
import MessageInput from './MessageInput.vue'
import { useChatStore } from '@/stores/chat'
import { useUserStore } from '@/stores/user'
import type { Message } from '@/types'

interface Props {
  loading?: boolean
}

const props = withDefaults(defineProps<Props>(), {
  loading: false
})

const emit = defineEmits<{
  error: [error: string]
  retry: []
}>()

const chatStore = useChatStore()
const userStore = useUserStore()

const error = ref('')
const messagesLoading = ref(false)
const retryCount = ref(0)
const maxRetries = 3

// 计算属性
const messages = computed(() => chatStore.activeChatMessages)
const typingUsers = computed(() => chatStore.activeChatTypingUsers)
const activeChat = computed(() => chatStore.activeChatData)
const currentUser = computed(() => userStore.currentUser)

const hasMoreMessages = computed(() => {
  // TODO: 实现基于实际数据的判断
  return messages.value.length > 0 && messages.value.length % 20 === 0
})

const inputPlaceholder = computed(() => {
  if (!activeChat.value) return '请选择一个聊天'
  if (activeChat.value.status === 'closed') return '聊天已关闭'
  return '输入消息...'
})

const inputDisabled = computed(() => {
  return !activeChat.value || 
         activeChat.value.status === 'closed' || 
         props.loading || 
         !!error.value
})

// 方法
const handleSendMessage = async (content: string, type: 'text' | 'image' | 'file' = 'text') => {
  if (!activeChat.value || !currentUser.value) {
    setError('无法发送消息：缺少必要信息')
    return
  }

  try {
    await chatStore.sendMessage(content, type)
    clearError()
  } catch (err) {
    const errorMessage = err instanceof Error ? err.message : '发送消息失败'
    setError(errorMessage)
  }
}

const handleTyping = (isTyping: boolean) => {
  if (!activeChat.value || !currentUser.value) return

  try {
    if (isTyping) {
      chatStore.addTypingUser(activeChat.value.id, currentUser.value.id)
    } else {
      chatStore.removeTypingUser(activeChat.value.id, currentUser.value.id)
    }
  } catch (err) {
    console.warn('Failed to update typing status:', err)
  }
}

const handleLoadMore = async () => {
  if (!activeChat.value || messagesLoading.value) return

  try {
    messagesLoading.value = true
    clearError()
    
    // TODO: 实现加载更多消息的逻辑
    await chatStore.loadChatMessages(activeChat.value.id)
    
  } catch (err) {
    const errorMessage = err instanceof Error ? err.message : '加载消息失败'
    setError(errorMessage)
  } finally {
    messagesLoading.value = false
  }
}

const handleRetry = async () => {
  if (retryCount.value >= maxRetries) {
    setError('重试次数过多，请刷新页面')
    return
  }

  try {
    retryCount.value++
    clearError()
    emit('retry')
    
    // 重新加载当前聊天
    if (activeChat.value) {
      await chatStore.loadChatMessages(activeChat.value.id)
    }
    
    retryCount.value = 0
  } catch (err) {
    const errorMessage = err instanceof Error ? err.message : '重试失败'
    setError(errorMessage)
  }
}

const setError = (message: string) => {
  error.value = message
  emit('error', message)
}

const clearError = () => {
  error.value = ''
}

// 监听活跃聊天变化
watch(() => chatStore.activeChat, async (newChatId, oldChatId) => {
  if (newChatId !== oldChatId) {
    clearError()
    retryCount.value = 0
    
    if (newChatId) {
      try {
        // 加载新聊天的消息
        if (!messages.value.length) {
          await chatStore.loadChatMessages(newChatId)
        }
      } catch (err) {
        const errorMessage = err instanceof Error ? err.message : '加载聊天失败'
        setError(errorMessage)
      }
    }
  }
})

// 监听聊天store的错误
watch(() => chatStore.error, (newError) => {
  if (newError) {
    setError(newError)
  }
})

// 组件挂载时的初始化
onMounted(async () => {
  try {
    // 如果有活跃聊天但没有消息，则加载消息
    if (activeChat.value && !messages.value.length) {
      await chatStore.loadChatMessages(activeChat.value.id)
    }
  } catch (err) {
    const errorMessage = err instanceof Error ? err.message : '初始化失败'
    setError(errorMessage)
  }
})

// 组件卸载时清理
onUnmounted(() => {
  // 清除正在输入状态
  if (activeChat.value && currentUser.value) {
    chatStore.removeTypingUser(activeChat.value.id, currentUser.value.id)
  }
})
</script>

<style scoped>
.chat-mid {
  flex: 1;
  display: flex;
  flex-direction: column;
  height: 100%;
  background: var(--color-background);
}

.error-boundary {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 32px;
}

.error-content {
  text-align: center;
  max-width: 400px;
}

.error-content .icon-error {
  font-size: 48px;
  color: var(--color-error);
  margin-bottom: 16px;
  display: block;
}

.error-content h3 {
  margin: 0 0 8px 0;
  color: var(--color-text);
  font-size: 18px;
}

.error-content p {
  margin: 0 0 24px 0;
  color: var(--color-text-secondary);
  line-height: 1.5;
}

.retry-btn {
  padding: 8px 24px;
  background: var(--color-primary);
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.2s;
}

.retry-btn:hover {
  background: var(--color-primary-dark);
}

.loading-state {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 16px;
  color: var(--color-text-secondary);
}

.loading-spinner {
  width: 32px;
  height: 32px;
  border: 3px solid var(--color-border);
  border-top: 3px solid var(--color-primary);
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

.chat-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  height: 100%;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

/* 图标样式 */
.icon-error::before {
  content: '⚠️';
}

/* 响应式设计 */
@media (max-width: 768px) {
  .error-boundary {
    padding: 24px 16px;
  }
  
  .error-content {
    max-width: 100%;
  }
  
  .error-content .icon-error {
    font-size: 36px;
  }
  
  .error-content h3 {
    font-size: 16px;
  }
}
</style>